#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PIL import Image
import ctypes  
import win32process
import win32api
import urlparse
import os
import httplib
import socket
import sys
import logging

TEMP_DIRECTORY = win32api.GetTempPath()
CURRENT_DIRECTORY = os.getcwd()

class adlogging:
    def __init__(self):
        # set up logging to file - see previous section for more details
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                            datefmt='%m-%d %H:%M',
                            filename=os.path.join(CURRENT_DIRECTORY, 'adlogging.txt'),
                            filemode='w')
        # define a Handler which writes INFO messages or higher to the sys.stderr
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        # set a format which is simpler for console use
        formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
        # tell the handler to use this format
        console.setFormatter(formatter)
        # add the handler to the root logger
        logging.getLogger('').addHandler(console)
    
    def getlogger(self,loger_name=None):
        return logging.getLogger(loger_name)
    
root_log = adlogging()
ad_logging = root_log.getlogger()
    
def set_current_process_priority(level='low'):
    current_handle = win32process.GetCurrentProcess()
    if level == 'low':
        win32process.SetPriorityClass(current_handle, win32process.IDLE_PRIORITY_CLASS)
    elif level == 'normal':
        win32process.SetPriorityClass(current_handle, win32process.NORMAL_PRIORITY_CLASS)
    elif level == 'high':
        win32process.SetPriorityClass(current_handle, win32process.HIGH_PRIORITY_CLASS)
    else:
        pass
    
def setWallpaperFromBMP(imagepath):  
    SPI_SETDESKWALLPAPER = 20 # According to http://support.microsoft.com/default.aspx?scid=97142  
    ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, imagepath , 0) #SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE  
   
def setWallPaper(imagePath):  
    """Given a path to an image, convert it to bmp and set it as wallpaper"""  
    bmpImage = Image.open(imagePath)  
    newPath = TEMP_DIRECTORY + 'wallpaper.bmp'
    bmpImage.save(newPath, "BMP")  
    setWallpaperFromBMP(newPath)  

def get_file( f_url, f_save_to_dir=None, f_name=None, f_type='w' ):
    '''
    
    @param f_url: file url to download
    @param f_save_to_dir: where to save it
    @param f_name: file name to save
    @param f_type: file write type, 'wb' or 'w'
    '''
    
    log = root_log.getlogger('get file')
    protocol, host_port, path, parm, fragments = urlparse.urlsplit( f_url )
    
    if f_save_to_dir == None:
        get_file_save_path = os.path.split( path )[0]
    else:
        get_file_save_path = f_save_to_dir
    
    if f_name == None:
        get_file_base_name = os.path.basename( path )
    else:
        get_file_base_name = f_name
    
    get_file_full_path =  os.path.join( get_file_save_path, get_file_base_name )
    log.info('Get file full path:%s' % get_file_full_path) 
    try:
        u = httplib.HTTPConnection( host_port )
        u.request( 'GET', path )
        res = u.getresponse()
        log.info('Open Socket success. stats: %s %s' % ( res.status, res.reason ))
    except socket.error, ( errno, strerror ):
        u.close()
        log.info( 'Open Socket False. %s: %s' % ( errno, strerror ))
        return False
    
    if os.path.exists( os.path.split( get_file_full_path )[0] ):
        log.info('Path exists: %s' % os.path.split( get_file_full_path )[0])
    else:
        log.info('Path not exists: %s, we should create it' % os.path.split( get_file_full_path )[0])
        try:
            os.makedirs( os.path.split( get_file_full_path )[0] )
        except ( errno, strerror ):
            log.info('Create path Error %s: %s' % ( errno, strerror ))
            return False
    
    try:
        f = open( get_file_full_path, f_type )
        log.info('Open File Success %s' % get_file_full_path)
        if res.status != 200:
            f.write( res.reason )
            f.close()
            u.close()
            log.info('File not exists on url %s %s' % ( res.status, res.reason ))
            return False
        else:
            f.write( res.read() )
            f.close()
            u.close()
            log.info('File exists on url %s %s, download and save it' % ( res.status, res.reason ))
            return True
    except :
        u.close()
        log.info('Write File Error: %s ' % sys.exc_info()[0])
        return False
    
def _test():
    ad_logging.info('start...')
    get_file('http://i.spilot.com.cn/medias/update/update.ini',f_save_to_dir='C:/abc', f_name='a.ini')
    b = root_log.getlogger('ok')
    b.info('stop')
    
if __name__ == '__main__':
    _test()